package ar.com.binarit

import ar.com.binarit.entities.ParametrosSistema

class MailBuffer {

	String asunto
	String texto
	List mails

	public EnvioMail enviarMail(Map mapaInfo) {
		def textoSinEnters = texto.replaceAll("\n", "")
		def textoNuevo = parsearMail(mapaInfo, textoSinEnters)
		def asuntoSinEnters = asunto.replaceAll("\n", "")
		def asuntoNuevo = parsearMail(mapaInfo, asuntoSinEnters)
		String from = ParametrosSistema.list().first().mailEmisorMubbia
		return new EnvioMail(to: mails, from: from, subject: asuntoNuevo, mail: textoNuevo)
	}
		
	private def parsearMail(Map mapaInfo, String textoOriginal) {
		try {
			def textoNuevo = textoOriginal.replaceAll("\\{", "" + /\$/)
			textoNuevo = textoNuevo.replaceAll("}", "")
			Binding binding = new Binding()
			mapaInfo.each { info -> binding.setVariable(info.key, info.value) }
			
			GroovyShell shell = new GroovyShell(binding)
			def codigo = "def texto = \"" + textoNuevo + "\""
			return shell.evaluate(codigo)
		} catch (Exception e) {
			return "Al parsear: " + textoOriginal + " - error: " + e.getMessage()
		}
	}

	public String toString() {
		println "texto: ${texto}"
		return "Mail a " + mails + ", asunto: " + asunto
	}
}

